import * as XLSX from "xlsx";

export function excelToJson(
  raw: File,
  isPer?: boolean
): Promise<Record<string, any>[]> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    reader.onload = (e) => {
      try {
        const data = e.target?.result as ArrayBuffer;
        const workbook = XLSX.read(data, { type: "array" });
        const sheetName = workbook.SheetNames[0]; // 获取第一个工作表
        const worksheet = workbook.Sheets[sheetName];
        const jsonData = XLSX.utils.sheet_to_json(worksheet) as Record<
          string,
          any
        >[];
        if (isPer) {
          // 百分比转化
          jsonData.forEach((row: Record<string, any>) => {
            for (const key in row) {
              if (typeof row[key] === "number" && row[key] <= 1) {
                row[key] = `${(row[key] * 100).toFixed(4)}%`;
              }
            }
          });
        }

        resolve(jsonData);
      } catch (error) {
        reject(error);
      }
    };

    reader.onerror = (error) => {
      reject(error);
    };

    reader.readAsArrayBuffer(raw); // 读取文件内容
  });
}

export function downloadJson(json: any, name: string) {
  const blob = new Blob([JSON.stringify(json)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = name || "data.json";
  link.click();
  URL.revokeObjectURL(url);
  // 保存到当前路劲的file文件内
  // saveAs(blob, name || "data.json");

  return link;
}

export function getJsonDataByFile(fileList: any, index: number = 0) {
  return new Promise((resolve, reject) => {
    if (fileList.value.length === 0) {
      reject("请先上传文件");
    }
    const file = fileList.value[index].raw; // 获取第一个文件的原始文件对象
    if (!file) {
      reject("文件无效");
    }
    const reader = new FileReader();
    reader.onload = (event) => {
      try {
        const jsonContent = JSON.parse(event.target?.result as string); // 解析 JSON 内容
        resolve(jsonContent);
      } catch (error) {
        reject("文件内容无效");
      }
    };
    reader.readAsText(file); // 以文本形式读取文件
  });
}
function saveAs() {
  return new Promise((resolve, reject) => {});
}
